<template>
	<view>
		<tn-nav-bar fixed >销售数据</tn-nav-bar>
  <view class="container">
    <!-- 顶部导航栏 -->

    <!-- 销售统计卡片 -->
    <view class="stat-section">
      <view class="data-cards">
        <!-- 最上侧大卡片:今日销售 -->
        <view class="left-column">
          <view class="stat-card today-card">
            <view class="card-title">今日销售</view>
            <view class="sales-amount">¥ {{formatMoney(todayData.salesFee)}}</view>
            <view class="count-row">
              <view class="count-item">
                <text class="label">订单数</text>
                <text class="num">{{todayData.orderCnt}}</text>
              </view>
              <view class="count-item">
                <text class="label">顾客数</text>
                <text class="num">{{todayData.custCnt}}</text>
              </view>
            </view>
          </view>
        </view>

        <!-- 下侧两个小卡片 -->
        <view class="right-column">
          <view class="stat-card period-card">
            <view class="card-title">近7天</view>
            <view class="sales-amount">¥ {{formatMoney(weekData.salesFee)}}</view>
            <view class="count-row">
              <view class="count-item">
                <text class="label">订单数</text>
                <text class="num">{{weekData.orderCnt}}</text>
              </view>
              <view class="count-item">
                <text class="label">顾客数</text>
                <text class="num">{{weekData.custCnt}}</text>
              </view>
            </view>
          </view>

          <view class="stat-card period-card">
            <view class="card-title">近30天</view>
            <view class="sales-amount">¥ {{formatMoney(monthData.salesFee)}}</view>
            <view class="count-row">
              <view class="count-item">
                <text class="label">订单数</text>
                <text class="num">{{monthData.orderCnt}}</text>
              </view>
              <view class="count-item">
                <text class="label">顾客数</text>
                <text class="num">{{monthData.custCnt}}</text>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>

  <!-- 近7天门店销售 -->
  <view class="chart-card">
		<view class="chart-title">近7天门店销售</view>
		<view class="chart-container">
		  <qiun-data-charts 
			type="column"
			:opts="storeOpts"
			:chartData="storeChartData"
			background="none"
		  />
		</view>
  </view>
    
   <!-- 近30天销售趋势 -->
   <view class="chart-card">
    <view class="chart-title">近30天销售趋势</view>
    <view class="chart-container">
      <qiun-data-charts 
        type="mix"
        :opts="monthOpts"
        :chartData="monthChartData"
        background="none"
      />
    </view>
  </view>

    <!-- 门店销售分布 -->
    <view class="chart-card">
      <view class="chart-header">
        <text class="chart-title">门店销售分布</text>
      </view>
      <view class="chart-container">
        <qiun-data-charts 
          type="pie"
          :opts="pieOpts"
          :chartData="pieData"
          background="none"
          :canvas2d="true"
          :ontouch="true"
        />
      </view>
    </view>
	
	<!-- 房间销售排行(未实现，可以删掉) -->
    <view class="chart-card">
		<view class="chart-header">
		  <text class="chart-title">房间销售排行</text>
		</view>
		<view class="chart-container">
		  <qiun-data-charts 
			type="bar"
			:opts="roomRankOpts"
			:chartData="roomRankData"
			background="none"
		  />
		</view>
	</view>
	
	
  </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      // 统计数据
      todayData: {
        salesFee: 0,
        custCnt: 0,
        orderCnt: 0
      },
      weekData: {
        salesFee: 0,
        custCnt: 0,
        orderCnt: 0
      },
      monthData: {
        salesFee: 0,
        custCnt: 0,
        orderCnt: 0
      },

      // 周数据图表配置
      weekChartData: {
        categories: [],
        series: [
          {
            name: "销售额",
            data: []
          },
          {
            name: "顾客数",
            data: []
          },
          {
            name: "订单数",
            data: []
          }
        ]
      },

      // 月数据图表配置  
      monthChartData: {
        categories: [],
        series: [
          {
            name: "销售额",
            type: "line",
            data: [],
            index: 1,
            format: "¥ {value}"
          },
          {
            name: "顾客数",
            type: "column",
            data: []
          },
          {
            name: "订单数",
            type: "column",
            data: []
          }
        ]
      },

        // 周数据图表配置
           weekOpts: {
             color: ["#1890FF", "#EE6666"],
             padding: [15, 15, 0, 5],
             enableScroll: false,
             legend: {
               show: true,
               position: 'top',
               float: 'right',
               padding: 15,
               margin: 10,
               fontSize: 14
             },
             xAxis: {
               disableGrid: true,
               rotateLabel: true,
               rotateAngle: 45,
               fontSize: 14,
               margin: 20
             },
             yAxis: {
               data: [{
                 min: 0,
                 max: 3500,
                 splitNumber: 7,
                 fontSize: 14,
                 formatter: (val) => {
                   return val + '元'
                 }
               }]
             },
             extra: {
               column: {
                 type: "group",
                 width: 40,
                 activeBgColor: "#000000",
                 activeBgOpacity: 0.08,
                 seriesGap: 6,
                 categoryGap: 6,
                 barBorderRadius: [6, 6, 6, 6]
               }
             }
           },
      
      monthOpts: {
            color: ["#1890FF","#91CB74","#FAC858"],
            padding: [5, 5, 0, 5],
            enableScroll: false,
            legend: {},
            xAxis: {
              disableGrid: true,
              fontSize: 11,
              margin: 8,
              format: function(val) {
                return val.substring(0, 2) + '-' + val.substring(2);
              }
            },
            yAxis: {
              disabled: false,
              disableGrid: false,
              splitNumber: 5,
              gridType: "dash",
              dashLength: 4,
              gridColor: "#CCCCCC",
              padding: 10,
              data: [
                {
                  position: "left",
                  title: "销售额",
                  titleFontSize: 12,
                  min: 0,
                  max: 4000,
                  unit: "元"
                },
                {
                  position: "right",
                  title: "数量",
                  titleFontSize: 12,
                  min: 0,
                  max: 30,
                  unit: "个",
                  textAlign: "left"
                }
              ]
            },
            extra: {
              mix: {
                column: {
                  width: 15,
                  barBorderRadius: [2, 2, 0, 0],
                  activeBgColor: "#000000",
                  activeBgOpacity: 0.08
                }
              },
              line: {
                type: "straight",
                width: 2.5,
                activeType: "hollow"
              }
            },
            dataLabel: false
          },
      // 门店销售图表分布
      storeChartData: {
        categories: [],
        series: []
      },

      // 门店销售图表配置
      storeOpts: {
        color: ['#1890FF', '#91CB74'], // 两个门店的颜色
        padding: [15, 15, 15, 15],
        legend: {
          show: true,
          position: 'top'
        },
        xAxis: {
          disableGrid: true,
          rotateLabel: true // 旋转标签避免重叠
        },
        yAxis: {
          gridType: 'dash',
          dashLength: 2,
          data: [{
            min: 0
          }]
        },
        extra: {
          column: {
            type: 'group',
            width: 30,
            activeBgColor: '#000000',
            activeBgOpacity: 0.08
          }
        }
      },

      // 门店销售分布数据
      pieData: {
        categories: [],
        series: [{
          name: "销售额",
          data: []
        }]
      },
    // 饼图配置
      pieOpts: {
        padding: [15, 15, 0, 15],
        title: {
          text: '门店销售分布',
          top: 20,
          left: 'center'
        },
        legend: {
          show: true,
          position: 'bottom',
          itemWidth: 25,
          itemHeight: 14,
          textStyle: {
            color: '#666',
            fontSize: 12
          }
        },
        tooltip: {
          trigger: 'item',
          formatter: '{b}: ¥{c} ({d}%)'
        },
        series: [{
          type: 'pie',
          radius: '65%',
          center: ['50%', '50%'],
          itemStyle: {
            borderRadius: 0,
            borderColor: '#fff',
            borderWidth: 2
          },
          label: {
            show: false
          },
          emphasis: {
            label: {
              show: true,
              fontSize: 14,
              fontWeight: 'bold'
            }
          }
        }]
      },
      pieData: {
        series: []
      },
  

            // 房间销售排行配置
            roomRankOpts: {
             color: ["#1890FF"],
             padding: [15, 60, 0, 40],
             enableScroll: false,
             legend: {
               show: false
             },
             xAxis: {
               boundaryGap: "justify",
               disableGrid: true,
               min: 0,
               max: 5000,
               formatter: (val) => {
                 return val + '元'
               }
             },
             yAxis: {
               data: [{
                 disabled: true,
                 position: "left",
                 axisLine: false,
                 title: "房间"
               }]
             },
             extra: {
               bar: {
                 type: "stack",
                 width: 20,
                 meterBorde: 0,
                 barBorderRadius: [0, 4, 4, 0],
                 linearType: "none"
               }
             }
           },
      // 房间销售排行数据
             roomRankData: {
             categories: [
             ],
             series: [{
               name: "销售额",
               data: []
             }]
           }
   }    
  },

  onLoad() {
    this.getChartData()
    this.getStoreData() // 添加获取门店数据
    this.getPieData() // 添加获取饼图数据
    this.getRoomRankData() // 添加获取房间排行数据
  },

  methods: {
    getChartData() {
	  //发送POST请求填充周数据图表、月数据图表以及计算今日、本周和本月的统计数据_已完成
      uni.$u.http.post('/system/report/rangeTrendData').then(res => {
        if(res.resultCode === 0) {
          const { xData, salesFeeData, custCntData, orderCntData } = res.data
          
          // 格式化日期
          const formatDates = xData.map(date => {
            return date.substring(4,6) + '-' + date.substring(6,8)
          })

          // 更新周数据(最近7天)
          this.weekChartData.categories = formatDates.slice(-7)
          this.weekChartData.series[0].data = salesFeeData.slice(-7)
          this.weekChartData.series[1].data = custCntData.slice(-7)
          this.weekChartData.series[2].data = orderCntData.slice(-7)

          // 更新月数据(全部数据)
          this.monthChartData.categories = formatDates
          this.monthChartData.series[0].data = salesFeeData
          this.monthChartData.series[1].data = custCntData
          this.monthChartData.series[2].data = orderCntData

          // 更新今日数据
          const lastIndex = salesFeeData.length - 1
          this.todayData = {
            salesFee: salesFeeData[lastIndex],
            custCnt: custCntData[lastIndex],
            orderCnt: orderCntData[lastIndex]
          }
			console.log('今日数据'+this.todayData)
          // 算周数据
          this.weekData = {
            salesFee: salesFeeData.slice(-7).reduce((a,b) => a+b, 0),
            custCnt: custCntData.slice(-7).reduce((a,b) => a+b, 0),
            orderCnt: orderCntData.slice(-7).reduce((a,b) => a+b, 0)
          }
			console.log('本周数据'+this.weekData)
          // 计算月数据(全部)
          this.monthData = {
            salesFee: salesFeeData.reduce((a,b) => a+b, 0),
            custCnt: custCntData.reduce((a,b) => a+b, 0),
            orderCnt: orderCntData.reduce((a,b) => a+b, 0)
          }
		  console.log('本月数据'+this.monthData)
		  // 填充近30天图表数据
		  this.monthChartData = {
		    categories: formatDates,
		    series: [{
		  	name: '销售额',
		  	type: 'line',
		  	data: salesFeeData
		    }, {
		  	name: '顾客数',
		  	type: 'column',
		  	data: custCntData
		    }, {
		  	name: '订单数',
		  	type: 'column',
		  	data: orderCntData
		    }]
		  }
        }
	  })
	},

    // 获取门店销售数据
    getStoreData() {
      //获取关于门店销售的趋势数据用于更新销售趋势图_已完成
      uni.$u.http.post('/system/report/mchTrendData').then(res => {
        if(res.resultCode === 0) {
          const { mchList, xData, sData } = res.data

          // 格式化日期
          const formatDates = xData.map(date => {
            return date.substring(4,6) + '-' + date.substring(6,8)
          })

          // 更新图表数据
          this.storeChartData = {
            categories: formatDates,
            series: sData.map(item => ({
              name: item.name,
              data: item.data.map(val => parseFloat(val).toFixed(2))
            }))
          }
		  
		
        }
      })
    },

    // 获取门店销售分布数据
    getPieData() {
	  //获取关于门店销售分布的数据用于门店销售分布图_已完成
      uni.$u.http.post('/system/report/mchSalesData').then(res => {
        if(res.resultCode === 0) {
          // 更新饼图数据结构
          this.pieData = {
            categories: res.data.map(item => item.name),
            series: [{
              name: "销售额",
              data: res.data.map(item => ({
                name: item.name,
                value: parseFloat(item.value)
              }))
            }]
          }
          console.log('饼图数据:', this.pieData) // 调试用
        }
      })
    },

  //   // 获取房间销售排行数据
  //   getRoomRankData() {
  //     uni.$u.http.post('/system/report/roomSalesData').then(res => {
  //       if(res.resultCode === 0 && res.data) {
  //         const { sData = [], yData = [] } = res.data
  
  //         this.roomRankData = {
  //           categories: processedData.map(item => item.name),
  //           series: [{
  //             name: "销售额",
  //             data: processedData.map(item => item.value)
  //           }]
  //         }
          
  //         // 更新Y轴数据
  //         this.roomRankOpts.yAxis.data = this.roomRankData.categories
          
  //       } else {
  //         this.handleEmptyRoomData()
  //       }
  //     }).catch(err => {
  //       console.error('获取房间销售数据出错:', err)
  //       this.handleEmptyRoomData()
  //     })
  //   },

  //   // 添加处理空数据的辅助方法
  //   handleEmptyRoomData() {
  //     const emptyData = {
  //       categories: [],
  //       series: [{
  //         name: "销售额",
  //         data: []
  //       }]
  //     }
  //     this.roomRankData = emptyData
  //     this.roomRankOpts.yAxis.data = []
  //   },

    // 添加金额格式化方法
    formatMoney(num) {
      return parseFloat(num || 0).toFixed(2)
    }
  }
}
</script>

<style lang="scss" scoped>
.container {
  padding: 20rpx;
  background-color: #f8f9fa;
  min-height: 100vh;
}

.stat-section {
  margin-top: 70px;  // 为顶部导航栏留出空间
  padding: 20rpx;
}

.data-cards {
  display: flex;
  gap: 20rpx;
}

// 左侧今日销售卡片
.left-column {
  flex: 1.2;
  
  .today-card {
    height: 100%;
    background: linear-gradient(135deg, #2979ff, #1890FF);
    color: #fff;
    transition: transform 0.3s ease;
    
    &:hover {
      transform: translateY(-3px);
    }
    
    .card-title {
      font-size: 32rpx;
      font-weight: 500;
      opacity: 0.9;
    }
    
    .sales-amount {
      font-size: 76rpx;
      margin: 40rpx 0;
      font-weight: 600;
      text-shadow: 0 2px 4px rgba(0,0,0,0.1);
    }
  }
}

// 右侧周期卡片
.right-column {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 20rpx;
  
  .period-card {
    flex: 1;
    background: #fff;
    transition: transform 0.3s ease;
    border: 1px solid rgba(0,0,0,0.05);
    
    &:hover {
      transform: translateY(-3px);
    }
    
    .sales-amount {
      font-size: 52rpx;
      margin: 20rpx 0;
      color: #2979ff;
      font-weight: 600;
    }
  }
}

// 通用卡片样式
.stat-card {
  border-radius: 20rpx;
  padding: 30rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.08);

  .card-title {
    font-size: 28rpx;
    opacity: 0.85;
    font-weight: 500;
  }
}

// 计数行样式
.count-row {
  display: flex;
  justify-content: space-between;
  margin-top: 30rpx;
  
  .count-item {
    text-align: center;
    padding: 10rpx 20rpx;
    border-radius: 12rpx;
    background: rgba(255,255,255,0.1);
    
    .label {
      display: block;
      font-size: 24rpx;
      opacity: 0.85;
      margin-bottom: 8rpx;
    }
    
    .num {
      font-size: 36rpx;
      font-weight: 600;
    }
  }
}

// 图表卡片样式
.chart-card {
  background: #fff;
  border-radius: 20rpx;
  padding: 30rpx;
  margin: 30rpx 20rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.06);
  transition: transform 0.3s ease;

  &:hover {
    transform: translateY(-3px);
  }

  .chart-title {
    font-size: 32rpx;
    font-weight: 600;
    color: #333;
    margin-bottom: 30rpx;
    padding-left: 24rpx;
    border-left: 8rpx solid #2979ff;
    display: flex;
    align-items: center;
  }

  .chart-container {
    height: 600rpx;
    padding: 20rpx;
  }
}

// 图表容器样式优化
.chart-container {
  position: relative;
  
  &::after {
    content: '';
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
    height: 40rpx;
    background: linear-gradient(to top, rgba(255,255,255,1), rgba(255,255,255,0));
    pointer-events: none;
  }
}

// 饼图特殊样式
.chart-card:nth-child(4) {  // 门店销售分布图表
  .chart-container {
    height: 600rpx;  // 调整为更合适的高度
    padding: 10rpx;
    display: flex;
    justify-content: center;
    align-items: center;
    
    :deep(.ucharts-legend) {
      right: 40rpx !important;
      
      .item {
        margin: 15rpx 0;
        display: flex;
        align-items: center;
        
        .item-label {
          font-size: 26rpx;
          color: #666;
          margin-right: 10rpx;
        }
        
        .item-value {
          font-size: 28rpx;
          color: #333;
          font-weight: 600;
        }
      }
    }
  }
}
.chart-card:last-child {
.chart-container {
height: 800rpx;
overflow: hidden; // 防止内容溢出
:deep(.ucharts-legend) {
display: none; // 隐藏图例
}
}
}
// 优化图表容器通用样式
.chart-container {
  position: relative;
  
  &::after {
    content: none; // 移除渐变效果，让饼图更清晰
  }
}

// 房间销售排行图表特殊样式
.chart-card:last-child {
  .chart-container {
    height: 800rpx;
    overflow: hidden;  // 防止内容溢出
    
    :deep(.ucharts-legend) {
      display: none;  // 隐藏图例
    }
  }
}

// 深色模式下的图例样式
:deep(.ucharts-legend) {
  .item-label {
    color: #666;
    font-size: 24rpx;
  }
  
  .item-value {
    color: #333;
    font-weight: 600;
    font-size: 26rpx;
  }
}

// 响应式调整
@media screen and (max-width: 768px) {
  .data-cards {
    flex-direction: column;
    
    .left-column,
    .right-column {
      flex: none;
    }
  }
  
  .stat-card {
    margin-bottom: 20rpx;
  }
}
</style>

